package com.xwder.example.filter;

import com.xwder.example.config.SysConfig;
import com.xwder.example.util.WebSpringBeanUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * xss
 *
 * @author xwder
 * @date 2021/3/31 10:14
 **/
//指定过滤器的执行顺序,值越大越靠后执行
@Order(1)
@Component
@WebFilter(filterName = "xssFilter", urlPatterns = "/*")
public class XssFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        SysConfig sysConfig = WebSpringBeanUtils.getBean(SysConfig.class);
        if (sysConfig != null) {
            String needFilterXss = sysConfig.getStr("system.need-filter-xss", "false");
            if ("true".equalsIgnoreCase(needFilterXss)) {
                XsslHttpServletRequestWrapper xssRequest = new XsslHttpServletRequestWrapper((HttpServletRequest) request);
                chain.doFilter(xssRequest, response);
            } else {
                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }
}
